package com.example.anitamusicspace.controller;

import com.example.anitamusicspace.mapper.LoveMusicMapper;
import com.example.anitamusicspace.mapper.MusicMapper;
import com.example.anitamusicspace.model.Music;
import com.example.anitamusicspace.model.User;
import com.example.anitamusicspace.service.LoveMusicService;
import com.example.anitamusicspace.service.MusicService;
import com.example.anitamusicspace.tools.Constant;
import com.example.anitamusicspace.tools.ResponseBodyMessage;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 小梅就是酱子
 * Date: 2022-08-02
 * Time: 18:08
 */
@RestController
@RequestMapping("/music")
public class MusicController {
    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Autowired
    private MusicService musicService;


    //之所以要注入收藏音乐的mapper是因为删除部分,当删除库中的音乐的时候，同步删除lovemusic中的数据
    @Autowired
    private LoveMusicService loveMusicService;

    //上传音乐
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer, @RequestParam("filename")
            MultipartFile file, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.检查是否登录了
        HttpSession httpSession = req.getSession(false);
        if (httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录,请先登录！");
            return new ResponseBodyMessage<>(-1, "没有登录,请先登录！", false);
        }


        //2.查询数据库中是否有当前音乐[歌曲名和歌手都一样],有就不再上传
        String filenameAndType = file.getOriginalFilename();//xxx.mp3
        System.out.println("filenameAndType--->>>>>>>>>>>>>>>>>" + filenameAndType);
        int index = filenameAndType.lastIndexOf(".");
        String title = filenameAndType.substring(0, index);
        List<Music> list = musicService.findMusicByMusicNameAndSinger(title);
        if(list != null){
            for(Music music : list) {
                if(music.getSinger().equals(singer)){
                    return new ResponseBodyMessage<>(-1,"当前歌手的歌曲已经存在!",false);
                }
            }
        }


        //3.上传到服务器
        String path = SAVE_PATH + "/" + filenameAndType;
        File dest = new File(path);
        System.out.println("dest:=>" + dest.getPath());
        if (!dest.exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest);//上传文件到目标
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "服务器上传失败！", false);
        }
        //判断上传的文件是不是mp3文件，不是的话就从服务器删掉
        File ff=new File(path);
        byte[] res = null;
        try {
            res = Files.readAllBytes(ff.toPath());
            String str = new String(res);
            if(!str.contains("TAG")) {
                ff.delete();
                return new ResponseBodyMessage<>(-1,"当前上传的不是mp3文件，请上传mp3文件",false);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器出现问题", false);
        }


        //4.进行数据库的上传
        //(1).准备数据 (2).调用insert
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();
        String url = "/music/get?path=" + title;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");//如果想获取的是精确到时分秒,yyyy-MM-dd HH:mm:ss
        String time = sf.format(new Date());

        try {
            int ret = 0;
            ret = musicService.insert(title, singer, time, url, userid);
            if (ret == 1) {
                resp.sendRedirect("/list.html");//前端实现好后需要更改，跳转页面!!!!!!!!!

                return new ResponseBodyMessage<>(0, "数据库上传成功！", true);
            } else {
                return new ResponseBodyMessage<>(-1, "数据库上传失败！", false);
            }
        } catch (BindingException e) {
            dest.delete();
            return new ResponseBodyMessage<>(-1, "数据库上传失败！", false);
        }
    }


    //------------------------------------------------------------------------------------------------------------------


    //播放音乐
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path) {
        File file=new File(SAVE_PATH+"/"+path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a==null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
//      return ResponseEntity.internalServerError().build();
//      return ResponseEntity.notFound().build();

    }

    //------------------------------------------------------------------------------------------------------------------

    //删除音乐
    //删除音乐----一次删除一个音乐
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id) {
        int iid = Integer.parseInt(id);
        Music music = musicService.findMusicById(iid);
        //看要删除的音乐的id是否存在
        //不存在就提示没有要删除的音乐
        if(music == null){
            return new ResponseBodyMessage<>(-1,"没有你要删除的音乐",false);
        }
        //存在就要删除数据库和服务器上此音乐的数据
        int ret = musicService.deleteMusicById(iid);
        //ret=1就代表数据库中删除了一条,因此接下来接着删服务器上的数据
        if(ret == 1) {
            int index = music.getUrl().lastIndexOf("=");
            String filename = music.getUrl().substring(index+1);
            File file = new File(SAVE_PATH+"/"+filename+".mp3");
            if(file.delete()) {
                //同步删除lovemusic表中的数据
                loveMusicService.deleteLoveMusicById(iid);
                return new ResponseBodyMessage<>(0,"删除服务器音乐成功",true);
            }else {
                return new ResponseBodyMessage<>(-1, "删除服务器音乐失败", false);
            }
            //ret!=1就代表数据库没删除成功
        }else{
            return new ResponseBodyMessage<>(-1,"删除数据库中的音乐失败",false);
        }
    }

    //删除音乐----一次删除多个音乐
    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id) {
        int sum = 0;
        for (int i = 0; i < id.size(); i++) {
            int musicId = id.get(i);
            Music music = musicService.findMusicById(musicId);
            int ret = musicService.deleteMusicById(musicId);
            if(ret == 1) {
                int index = music.getUrl().lastIndexOf("=");
                String filename = music.getUrl().substring(index+1);
                File file = new File(SAVE_PATH+"/"+filename+".mp3");
                if(file.delete()) {
                    //同步删除lovemusic表中的数据
                    loveMusicService.deleteLoveMusicById(musicId);
                    sum += ret;
                }else {
                    System.out.println("删除失败！");
                    return new ResponseBodyMessage<>(-1,"删除服务器上的音乐失败",false);
                }
            }else {
                System.out.println("删除失败！");
                return new ResponseBodyMessage<>(-1,"删除数据库中的音乐失败",false);
            }
        }
        if(sum == id.size()) {
            System.out.println("删除成功！");
            return new ResponseBodyMessage<>(0,"批量删除成功",true);
        }else {
            System.out.println("删除失败！");
            return new ResponseBodyMessage<>(0,"批量删除成功",false);
        }
    }

    //------------------------------------------------------------------------------------------------------------------

    //查询音乐
    @RequestMapping("/findmusic")//(required=false)可以不传入参数
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required=false) String musicName) {
        List<Music> musicList = null;
        if(musicName != null) {
            musicList = musicService.findMusicByMusicName(musicName);
        }else {
            //默认查询全部的音乐
            musicList = musicService.findMusic();
        }
        return new ResponseBodyMessage<>(0,"查询到了歌曲的信息",musicList);
    }



}
